package com.runen.wnhz.runen.ui.activity.mine;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.JumpUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.MyAnswerBean;
import com.runen.wnhz.runen.data.entity.MyQuestionBean;
import com.runen.wnhz.runen.data.entity.QuestionInfoBean;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.presenter.Contart.QuestionInfoContart;
import com.runen.wnhz.runen.presenter.iPresenter.IQuestionInfoPersenter;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.MyTestMainAdapter;
import com.runen.wnhz.runen.widget.Anticlockwise;
import com.runen.wnhz.runen.widget.TitleBuilder;

import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-13.
 */

public class TestMainActivity extends BaseActivity<IQuestionInfoPersenter> implements  QuestionInfoContart.View, Anticlockwise.OnTimeCompleteListener, View.OnClickListener {

    Anticlockwise chronometer;
    ListView test_list_view;
    TextView quest_type,cell_questname;

    private TextView tv_last;
    private TextView tv_next;
    List<String>  subjects = new ArrayList<>();

    private UserBean reqeustUser;
    MyTestMainAdapter testMainAdapter;

    String ltid;
    String current_ttid;

    List<MyAnswerBean> answerlist;



    @Override
    protected int getLayoutView() {
        return R.layout.test_main_activity_layout;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {
        switch (clicked) {
            case LEFT:
                finish();
                break;
            case MIDDLE:
                break;
            case RIGHT:
                break;
            default:
                break;
        }
    }

    @Override
    protected void initStart() {
        ltid = getIntent().getStringExtra("ltid");
        initUiAndListener();

    }
    

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setMiddleTitleText("单元测试")
                .setRightText("交卷")
                .setLeftDrawable(R.mipmap.icon_back)
                .seTitleBgRes(R.mipmap.bg_title)
                .setRightTextColor(ContextCompat.getColor(this, R.color.text_white))
                .setMiddleTitleTextColor(ContextCompat.getColor(this, R.color.text_white))
        ;
        mTitleBuilder.setRightTextClickEnable(true);
        mTitleBuilder.setRightTextOrImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getLearningLessonData2();
            }
        });
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }



    public void initUiAndListener() {
        answerlist = new ArrayList<>();
        initView();
        initAdapter();
        getLearningLessonData(getToken(),ltid,"",0);
//        test_list_view.setAdapter(testMainAdapter);

        test_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(test_list_view.getChoiceMode()==ListView.CHOICE_MODE_SINGLE){
                    int checkedItemPosition = test_list_view.getCheckedItemPosition();
                    boolean isContain = false;
                    for (int i = 0; i<answerlist.size() ; i++){
                        if(current_ttid.equals(answerlist.get(i).getTtid())){
                            answerlist.get(i).setMy_answer(checkedItemPosition+"");
                            isContain = true;
                            return;
                        }
                    }

                    if(!isContain){
                        MyAnswerBean answer = new MyAnswerBean();
                        answer.setMy_answer(""+checkedItemPosition);
                        answer.setTtid(current_ttid);
                        answerlist.add(answer);
                    }
                    Toast.makeText(mContext, "you chose item " + checkedItemPosition, Toast.LENGTH_SHORT).show();
                }else if(test_list_view.getChoiceMode()==ListView.CHOICE_MODE_MULTIPLE){
                    SparseBooleanArray checkedItemPositions = test_list_view.getCheckedItemPositions();
                    boolean isChecked = checkedItemPositions.get(position);
                    Toast.makeText(mContext, "item " + position + " isChecked=" + isChecked, Toast.LENGTH_SHORT).show();
                    boolean isContain = false;
                    for (int i = 0; i<answerlist.size() ; i++){
                        if(current_ttid.equals(answerlist.get(i).getTtid())){
                            String  multiId ="";
                            for(int j=0;j<checkedItemPositions.size();j++){
                               int piseid =  checkedItemPositions.keyAt(j);
                               multiId=multiId + ","+piseid;
                            }
                            answerlist.get(i).setMy_answer(multiId);
                            isContain = true;
                            return;
                        }
                    }

                    if(!isContain){
                        MyAnswerBean answer = new MyAnswerBean();
                        answer.setMy_answer(""+checkedItemPositions);
                        answer.setTtid(current_ttid);
                        answerlist.add(answer);
                    }

                }
                
               

               
            }
        });
        chronometer.setTimeFormat("HH:mm:ss");
        chronometer.setLabel("倒计时 ");
        chronometer.setOnTimeCompleteListener(this);
        chronometer.initTime(60*120);//秒钟
        chronometer.start();
    }
    
    private void initView(){
        cell_questname = findViewById(R.id.cell_questname);
        quest_type = findViewById(R.id.quest_type);
        chronometer = findViewById(R.id.test_chronometer);
        test_list_view = findViewById(R.id.test_list_view);
        tv_last = findViewById(R.id.tv_last);
        tv_next = findViewById(R.id.tv_next);

        tv_last.setOnClickListener(this);
        tv_next.setOnClickListener(this);
        
        
        test_list_view.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }

    @Override
    public void onTimeComplete() {
        ToastUtil.showToast("时间到");
    }
    
    private void initAdapter(){
      /*  testMainAdapter = new MyTestMainAdapter(mContext,subjects);
        test_list_view.setAdapter(testMainAdapter);*/
    }
    /** 做题 */
    private void getLearningLessonData(String pageNum,String ltid,String ttid,int top) {
        if (getToken() != null) {
            FormBody formBody = new FormBody.Builder().add("token", getToken()).add("ltid", ltid)
                    .add("ttid", ttid).add("top", ""+top)
                    .build();
            Request request = new Request.Builder().url(NetUtils.TEST_GETQUESTINFO).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleUserLesson(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        });
                    }
                }
            });
        }
    }

    private void handleUserLesson(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        QuestionInfoBean evaluationEntity = new Gson().fromJson(json, QuestionInfoBean.class);
                        if (evaluationEntity != null) {
                            if ("1".equals(evaluationEntity.getRe())) {
                                if (subjects.size() != 0) {
                                    subjects.clear();
                                }
                                subjects = evaluationEntity.getData().getTt_option();
                                current_ttid = evaluationEntity.getData().getTtid();
                                cell_questname.setText(evaluationEntity.getData().getTt_quest());

                                /**type = 1（单选） 2 （多选） 3（判断）*/
                                String type = evaluationEntity.getData().getTt_type();
                                if(type.equals("1")){
                                    quest_type.setText("单选");
                                    test_list_view.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                                    test_list_view.clearChoices();
                                }else if(type.equals("2")){
                                    quest_type.setText("多选选");
                                    test_list_view.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                                    test_list_view.clearChoices();
                                }else if(type.equals("3")){
                                    quest_type.setText("判断");
                                    test_list_view.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                                    test_list_view.clearChoices();
                                }
                                    testMainAdapter = new MyTestMainAdapter(mContext,subjects);
                                    test_list_view.setAdapter(testMainAdapter);
                                return;
                            } else if (evaluationEntity.getRe().equals("0")) {
                                ToastUtil.showToast("已经是最后一题了");
                            } else if (evaluationEntity.getRe().equals("-1")) {
                                ToastUtil.showToast(evaluationEntity.getInfo());
                                startActivity(new Intent(TestMainActivity.this, LoginForPersonalActivity.class));
                            }
                        }
                    }
                });
                }
            }
        }

    /**提交试卷*/
    private void getLearningLessonData2() {
        if (getToken() != null) {

            Gson gs = new Gson();
            String sb =  gs.toJson(answerlist);

            ToastUtil.showToast("当前数组集合：" + sb);
            FormBody formBody = new FormBody.Builder().add("token", getToken()).add("ltid", ltid)
                    .add("ltArr", sb)
                    .build();
            Request request = new Request.Builder().url(NetUtils.TEST_PUTTEST).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleUserLesson2(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        });
                    }
                }
            });
        }
    }

    private void handleUserLesson2(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        QuestionInfoBean evaluationEntity = new Gson().fromJson(json, QuestionInfoBean.class);
                        if (evaluationEntity != null) {
                            if ("1".equals(evaluationEntity.getRe())) {
                                String score = evaluationEntity.getData().getScore();
                                Intent intent = new Intent(mContext, AchievementActivity.class);
                                intent.putExtra("ltid" , ltid);
                                intent.putExtra("mytid","");
                                intent.putExtra("max_score",score);
                                mContext.startActivity(intent);
                                finish();
                                return;
                            } else if (evaluationEntity.getRe().equals("0")) {
                                ToastUtil.showToast("已经是最后一题了");
                            } else if (evaluationEntity.getRe().equals("-1")) {
                                ToastUtil.showToast(evaluationEntity.getInfo());
                                startActivity(new Intent(TestMainActivity.this, LoginForPersonalActivity.class));
                            }
                        }
                    }
                });
            }
        }
    }




    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_right_text:

                break;
            case R.id.tv_next:
                subjects.clear();
                if(isAnswerd()){
                getLearningLessonData(getToken(),ltid,current_ttid,0);
                }else{
                    ToastUtil.showToast("您还未答题");
                }
                break;
            case R.id.tv_last:
                subjects.clear();
                getLearningLessonData(getToken(),ltid,current_ttid,1);

                break;
            default:
                break;
        }
    }

public boolean isAnswerd(){
        boolean isanswer = false;
        for(int a = 0 ;a<answerlist.size();a++){
            if(answerlist.get(a).getTtid().equals(current_ttid)){
                isanswer = true;
            }
        }
        return isanswer;
}

    @Override
    public String getToken() {
        reqeustUser = ACacheUtlis.getInstance().getReqeustUser(this);
        return reqeustUser.getToken();
    }

    @Override
    public void onSuccess(QuestionInfoBean data) {

    }
}
